package com.jie.langlangmall.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.github.pagehelper.PageHelper;
import com.jie.langlangmall.common.constant.MessageConstant;
import com.jie.langlangmall.common.exception.ApiException;
import com.jie.langlangmall.dao.PmsProductCategoryAttributeRelationDao;
import com.jie.langlangmall.dao.PmsProductCategoryDao;
import com.jie.langlangmall.dto.PmsProductCategoryParam;
import com.jie.langlangmall.dto.PmsProductCategoryWithChildrenItem;
import com.jie.langlangmall.mapper.PmsProductCategoryAttributeRelationMapper;
import com.jie.langlangmall.mapper.PmsProductCategoryMapper;
import com.jie.langlangmall.mapper.PmsProductMapper;
import com.jie.langlangmall.model.*;
import com.jie.langlangmall.service.PmsProductCategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @Author Jie
 * @Date 2024/11/23
 * @Email 3217998214@qq.com
 * @Description 商品分类
 */
@Service
@Slf4j
public class PmsProductCategoryServiceImpl implements PmsProductCategoryService {

    @Autowired
    private PmsProductCategoryMapper productCategoryMapper;
    @Autowired
    private PmsProductCategoryDao productCategoryDao;
    @Autowired
    private PmsProductMapper productMapper;
    @Autowired
    private PmsProductCategoryAttributeRelationMapper productCategoryAttributeRelationMapper;
    @Autowired
    private PmsProductCategoryAttributeRelationDao productCategoryAttributeRelationDao;

    /**
     * 查询所有一级分类以及子分类
     *
     * @return
     */
    @Override
    public List<PmsProductCategoryWithChildrenItem> listWithChildren() {
        return productCategoryDao.listWithChildren();
    }

    /**
     * 分页查询
     *
     * @param parentId
     * @param pageSize
     * @param pageNum
     * @return
     */
    @Override
    public List<PmsProductCategory> list(Long parentId, Integer pageSize, Integer pageNum) {
        PageHelper.startPage(pageNum, pageSize);
        PmsProductCategoryExample example = new PmsProductCategoryExample();
        example.createCriteria().andParentIdEqualTo(parentId);
        example.setOrderByClause("sort desc");
        return productCategoryMapper.selectByExample(example);
    }

    /**
     * 根据ID获取商品分类信息
     *
     * @param id
     * @return
     */
    @Override
    public PmsProductCategory getItem(Long id) {
        return productCategoryMapper.selectByPrimaryKey(id);
    }

    /**
     * 删除商品分类
     *
     * @param id
     */
    @Override
    public void delete(Long id) {
        // 1. 查看当前分类是否有关联商品
        PmsProductExample productExample = new PmsProductExample();
        productExample.createCriteria().andProductCategoryIdEqualTo(id).andDeleteStatusEqualTo(0);
        long count = productMapper.countByExample(productExample);
        if (count > 0) {
            // 2. 如果有关联商品，则不能删除
            throw new ApiException(MessageConstant.CATEGORY_CONNECT_PRODUCT);
        }
        // 3. 如果未关联，查看当前分类下是否有子分类
        PmsProductCategoryExample categoryExample = new PmsProductCategoryExample();
        categoryExample.createCriteria().andParentIdEqualTo(id);
        count = productCategoryMapper.countByExample(categoryExample);
        if (count > 0) {
            // 4. 如果有子分类，不能删除
            throw new ApiException(MessageConstant.CATEGORY_EXIST_CHILD);
        }
        // 5. 检查分类是否关联着属性
//        PmsProductCategoryAttributeRelationExample relationExample = new PmsProductCategoryAttributeRelationExample();
//        relationExample.createCriteria().andIdEqualTo(id);
//        count = productCategoryAttributeRelationMapper.countByExample(relationExample);
//        if (count > 0) {
//            // 6. 如果分类关联着属性，不能删除
//            throw new ApiException(MessageConstant.CATEGORY_EXIST_ATTR);
//        }
        // 7. 删除
        productCategoryMapper.deleteByPrimaryKey(id);
    }

    /**
     * 修改导航栏状态
     *
     * @param ids
     * @param navStatus
     */
    @Override
    public void updateNavStatus(List<Long> ids, Integer navStatus) {
        PmsProductCategory category = new PmsProductCategory();
        category.setNavStatus(navStatus);
        PmsProductCategoryExample example = new PmsProductCategoryExample();
        example.createCriteria().andIdIn(ids);
        productCategoryMapper.updateByExampleSelective(category, example);
    }

    /**
     * 修改显示状态
     *
     * @param ids
     * @param showStatus
     */
    @Override
    public void updateShowStatus(List<Long> ids, Integer showStatus) {
        PmsProductCategory category = new PmsProductCategory();
        PmsProductCategoryExample example = new PmsProductCategoryExample();
        category.setShowStatus(showStatus);
        example.createCriteria().andIdIn(ids);
        productCategoryMapper.updateByExampleSelective(category, example);
    }

    /**
     * 新增商品分类
     *
     * @param param
     */
    @Override
    public void create(PmsProductCategoryParam param) {
        PmsProductCategory category = BeanUtil.copyProperties(param, PmsProductCategory.class);
        // 设置分类的等级
        setCategoryLevel(category);
        productCategoryMapper.insertSelective(category);
        // 创建属性关联
        List<Long> productAttributeIdList = param.getProductAttributeIdList();
        if (!CollUtil.isEmpty(productAttributeIdList)) {
            insertRelationList(category.getId(), productAttributeIdList);
        }
    }

    /**
     * 修改分类信息
     *
     * @param id
     * @param param
     */
    @Override
    public void update(Long id, PmsProductCategoryParam param) {
        // 1. 父分类的id不能是自己
        if (Objects.equals(id, param.getParentId())) {
            throw new ApiException(MessageConstant.SUBMIT_PARAM_ERROR);
        }
        PmsProductCategory category = BeanUtil.copyProperties(param, PmsProductCategory.class);
        category.setId(id);

        // 2. 更新关联的商品中的商品分类的名称
        PmsProduct product = new PmsProduct();
        product.setProductCategoryName(category.getName());
        PmsProductExample productExample = new PmsProductExample();
        productExample.createCriteria().andProductCategoryIdEqualTo(id);
        productMapper.updateByExampleSelective(product, productExample);

        // 3. 更新关联的属性信息
        if (!CollUtil.isEmpty(param.getProductAttributeIdList())) {
            // 先删除之前的关联信息
            deleteRelation(id);
            // 重新创建
            insertRelationList(id, param.getProductAttributeIdList());
        } else {
            // 删除关联信息
            deleteRelation(id);
        }
        // 4. 更新分类信息
        productCategoryMapper.updateByPrimaryKeySelective(category);
    }

    /**
     * 创建属性关联
     *
     * @param categoryId             商品分类ID
     * @param productAttributeIdList 相关属性ID集合
     */
    private void insertRelationList(Long categoryId, List<Long> productAttributeIdList) {
        // TODO: 之前就有的属性需要删除吗？
        List<PmsProductCategoryAttributeRelation> relationList = new ArrayList<>();
        for (Long attrId : productAttributeIdList) {
            PmsProductCategoryAttributeRelation relation = new PmsProductCategoryAttributeRelation();
            relation.setProductAttributeId(attrId);
            relation.setProductCategoryId(categoryId);
            relationList.add(relation);
        }
        productCategoryAttributeRelationDao.insertList(relationList);
    }

    /**
     * 删除分类关联的所有属性
     *
     * @param categoryId
     */
    private void deleteRelation(Long categoryId) {
        PmsProductCategoryAttributeRelationExample relationExample = new PmsProductCategoryAttributeRelationExample();
        relationExample.createCriteria().andProductCategoryIdEqualTo(categoryId);
        productCategoryAttributeRelationMapper.deleteByExample(relationExample);
    }

    /**
     * 根据分类的parentId设置分类的level
     *
     * @param productCategory
     */
    private void setCategoryLevel(PmsProductCategory productCategory) {
        //没有父分类时为一级分类
        if (productCategory.getParentId() == 0) {
            productCategory.setLevel(0);
        } else {
            //有父分类时选择根据父分类level设置
            PmsProductCategory parentCategory = productCategoryMapper.selectByPrimaryKey(productCategory.getParentId());
            if (parentCategory != null) {
                productCategory.setLevel(parentCategory.getLevel() + 1);
            } else {
                productCategory.setLevel(0);
            }
        }
    }

}
